// PWA组合式函数
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { PWAManager, OfflineStorageManager, PWAUtils } from '../utils/pwa'

/**
 * PWA组合式函数
 * @returns {object} PWA状态和方法
 */
export function usePWA() {
  const isOnline = ref(navigator.onLine)
  const updateAvailable = ref(false)
  const installPrompt = ref(null)
  const isInstalled = ref(PWAUtils.isInstalled())
  const cacheSize = ref('0 MB')
  const cacheUsage = ref({ used: 0, available: 0, percentage: 0 })
  const connectionType = ref('unknown')
  const connectionSpeed = ref('unknown')
  
  const pwaManager = new PWAManager()
  const storageManager = new OfflineStorageManager('pwa_cache', 1)
  
  // 初始化PWA管理器
  const initPWA = async () => {
    try {
      await pwaManager.registerServiceWorker()
      await storageManager.init()
      
      // 检查更新
      await checkForUpdates()
      
      // 获取缓存大小
      await updateCacheSize()
      
      // 获取连接信息
      updateConnectionInfo()
    } catch (error) {
      console.error('PWA initialization failed:', error)
    }
  }
  
  // 检查更新
  const checkForUpdates = async () => {
    try {
      // 检查是否有等待中的Service Worker
      if (pwaManager.registration && pwaManager.registration.waiting) {
        updateAvailable.value = true
      }
    } catch (error) {
      console.error('Update check failed:', error)
    }
  }
  
  // 更新应用
  const updateApp = async () => {
    try {
      await pwaManager.applyUpdate()
      updateAvailable.value = false
    } catch (error) {
      console.error('App update failed:', error)
    }
  }
  
  // 安装应用
  const installApp = async () => {
    try {
      const result = await PWAUtils.promptInstall()
      if (result && result.outcome === 'accepted') {
        isInstalled.value = true
        installPrompt.value = null
      }
      return result
    } catch (error) {
      console.error('App installation failed:', error)
      return null
    }
  }
  
  // 清除缓存
  const clearCache = async () => {
    try {
      await pwaManager.clearCache()
      await updateCacheSize()
    } catch (error) {
      console.error('Cache clear failed:', error)
    }
  }
  
  // 更新缓存大小
  const updateCacheSize = async () => {
    try {
      if ('storage' in navigator && 'estimate' in navigator.storage) {
        const estimate = await navigator.storage.estimate()
        const used = estimate.usage || 0
        const available = estimate.quota || 0
        const percentage = available > 0 ? Math.round((used / available) * 100) : 0
        
        cacheSize.value = formatBytes(used)
        cacheUsage.value = {
          used,
          available,
          percentage
        }
      }
    } catch (error) {
      console.error('Cache size update failed:', error)
    }
  }
  
  // 更新连接信息
  const updateConnectionInfo = () => {
    if ('connection' in navigator) {
      const connection = navigator.connection
      connectionType.value = connection.effectiveType || 'unknown'
      
      // 根据连接类型判断速度
      const speedMap = {
        'slow-2g': 'very-slow',
        '2g': 'slow',
        '3g': 'medium',
        '4g': 'fast'
      }
      
      connectionSpeed.value = speedMap[connection.effectiveType] || 'unknown'
    }
  }
  
  // 检查是否为慢速连接
  const isSlowConnection = () => {
    if ('connection' in navigator) {
      const connection = navigator.connection
      return connection.effectiveType === 'slow-2g' || connection.effectiveType === '2g'
    }
    return false
  }
  
  // 获取连接信息
  const getConnectionInfo = () => {
    if ('connection' in navigator) {
      const connection = navigator.connection
      return {
        effectiveType: connection.effectiveType || 'unknown',
        downlink: connection.downlink || 0,
        rtt: connection.rtt || 0,
        saveData: connection.saveData || false
      }
    }
    return null
  }
  
  // 同步离线数据
  const syncOfflineData = async () => {
    try {
      if (!isOnline.value) {
        throw new Error('当前处于离线状态，无法同步数据')
      }
      
      // 获取离线存储的数据
      const offlineData = await storageManager.getOfflineData('userActions')
      if (offlineData && offlineData.length > 0) {
        // TODO: 将离线数据同步到服务器
        console.log('同步离线数据:', offlineData)
        
        // 同步成功后清除离线数据
        await storageManager.deleteOfflineData('userActions')
      }
      
      return { success: true }
    } catch (error) {
      console.error('同步离线数据失败:', error)
      return { success: false, message: error.message }
    }
  }
  
  // 格式化字节数
  const formatBytes = (bytes) => {
    if (bytes === 0) return '0 B'
    
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }
  
  // 在线状态监听
  const handleOnline = () => {
    isOnline.value = true
    updateConnectionInfo()
  }
  
  const handleOffline = () => {
    isOnline.value = false
  }
  
  // 安装提示监听
  const handleBeforeInstallPrompt = (event) => {
    event.preventDefault()
    installPrompt.value = event
  }
  
  // 连接变化监听
  const handleConnectionChange = () => {
    updateConnectionInfo()
  }
  
  onMounted(() => {
    // 初始化PWA
    initPWA()
    
    // 添加事件监听器
    window.addEventListener('online', handleOnline)
    window.addEventListener('offline', handleOffline)
    window.addEventListener('beforeinstallprompt', handleBeforeInstallPrompt)
    
    if ('connection' in navigator) {
      navigator.connection.addEventListener('change', handleConnectionChange)
    }
  })
  
  onUnmounted(() => {
    // 移除事件监听器
    window.removeEventListener('online', handleOnline)
    window.removeEventListener('offline', handleOffline)
    window.removeEventListener('beforeinstallprompt', handleBeforeInstallPrompt)
    
    if ('connection' in navigator) {
      navigator.connection.removeEventListener('change', handleConnectionChange)
    }
  })
  
  return {
    isOnline,
    updateAvailable,
    installPrompt,
    isInstalled,
    isInstallable: installPrompt,
    cacheSize,
    cacheUsage,
    connectionType,
    connectionSpeed,
    applyUpdate: updateApp,
    installPWA: installApp,
    syncOfflineData,
    updateCacheUsage: updateCacheSize,
    clearCache,
    checkForUpdates,
    isSlowConnection,
    getConnectionInfo
  }
}

/**
 * 离线存储组合式函数
 * @param {string} dbName - 数据库名称
 * @param {number} version - 数据库版本
 * @returns {object} 存储状态和方法
 */
export function useOfflineStorage(dbName = 'offline_storage', version = 1) {
  const isReady = ref(false)
  const error = ref(null)
  
  const storageManager = new OfflineStorageManager(dbName, version)
  
  // 初始化存储
  const init = async () => {
    try {
      await storageManager.init()
      isReady.value = true
      error.value = null
    } catch (err) {
      error.value = err.message
      console.error('Offline storage initialization failed:', err)
    }
  }
  
  // 保存数据
  const save = async (storeName, data) => {
    try {
      await storageManager.save(storeName, data)
      return true
    } catch (err) {
      error.value = err.message
      console.error('Save failed:', err)
      return false
    }
  }
  
  // 获取数据
  const get = async (storeName, key) => {
    try {
      return await storageManager.get(storeName, key)
    } catch (err) {
      error.value = err.message
      console.error('Get failed:', err)
      return null
    }
  }
  
  // 删除数据
  const remove = async (storeName, key) => {
    try {
      await storageManager.delete(storeName, key)
      return true
    } catch (err) {
      error.value = err.message
      console.error('Remove failed:', err)
      return false
    }
  }
  
  // 清空存储
  const clear = async (storeName) => {
    try {
      await storageManager.clear(storeName)
      return true
    } catch (err) {
      error.value = err.message
      console.error('Clear failed:', err)
      return false
    }
  }
  
  // 获取所有数据
  const getAll = async (storeName) => {
    try {
      return await storageManager.getAll(storeName)
    } catch (err) {
      error.value = err.message
      console.error('GetAll failed:', err)
      return []
    }
  }
  
  // 获取数据数量
  const count = async (storeName) => {
    try {
      return await storageManager.count(storeName)
    } catch (err) {
      error.value = err.message
      console.error('Count failed:', err)
      return 0
    }
  }
  
  onMounted(() => {
    init()
  })
  
  return {
    isReady,
    error,
    save,
    get,
    remove,
    clear,
    getAll,
    count
  }
}

/**
 * 网络状态组合式函数
 * @returns {object} 网络状态
 */
export function useNetworkStatus() {
  const isOnline = ref(navigator.onLine)
  const connectionType = ref('unknown')
  const connectionSpeed = ref('unknown')
  const downlink = ref(0)
  const rtt = ref(0)
  
  // 更新连接信息
  const updateConnectionInfo = () => {
    if ('connection' in navigator) {
      const connection = navigator.connection
      connectionType.value = connection.effectiveType || 'unknown'
      downlink.value = connection.downlink || 0
      rtt.value = connection.rtt || 0
      
      // 根据连接类型判断速度
      const speedMap = {
        'slow-2g': 'very-slow',
        '2g': 'slow',
        '3g': 'medium',
        '4g': 'fast'
      }
      
      connectionSpeed.value = speedMap[connection.effectiveType] || 'unknown'
    }
  }
  
  // 网络质量评估
  const networkQuality = computed(() => {
    if (!isOnline.value) return 'offline'
    
    if (connectionSpeed.value === 'very-slow') return 'poor'
    if (connectionSpeed.value === 'slow') return 'fair'
    if (connectionSpeed.value === 'medium') return 'good'
    if (connectionSpeed.value === 'fast') return 'excellent'
    
    return 'unknown'
  })
  
  // 事件处理器
  const handleOnline = () => {
    isOnline.value = true
    updateConnectionInfo()
  }
  
  const handleOffline = () => {
    isOnline.value = false
  }
  
  const handleConnectionChange = () => {
    updateConnectionInfo()
  }
  
  onMounted(() => {
    updateConnectionInfo()
    
    window.addEventListener('online', handleOnline)
    window.addEventListener('offline', handleOffline)
    
    if ('connection' in navigator) {
      navigator.connection.addEventListener('change', handleConnectionChange)
    }
  })
  
  onUnmounted(() => {
    window.removeEventListener('online', handleOnline)
    window.removeEventListener('offline', handleOffline)
    
    if ('connection' in navigator) {
      navigator.connection.removeEventListener('change', handleConnectionChange)
    }
  })
  
  return {
    isOnline,
    connectionType,
    connectionSpeed,
    downlink,
    rtt,
    networkQuality
  }
}

export default {
  usePWA,
  useOfflineStorage,
  useNetworkStatus
}